<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card v-loading="isLoading">
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="addRoleList"
              >新增角色</el-button
            >
            <!-- 表格 -->
            <el-table :data="roleList">
              <el-table-column
                label="序号"
                width="100"
                type="index"
                :index="indexMethod"
              />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="success"
                    @click="showAssignDialogFn(scope.row.id)"
                    >分配权限</el-button
                  >
                  <el-button
                    size="small"
                    type="primary"
                    @click="editRoleList(scope.row.id)"
                    >编辑</el-button
                  >
                  <el-button
                    size="small"
                    type="danger"
                    @click.native="delRoleList(scope.row.id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页设置 -->
            <div
              style="margin-top: 10px; display: flex; justify-content: flex-end"
            >
              <!-- current-page 表示的当前是哪一页 -->
              <!-- page-sizes 动态设置页容量的下拉列表 -->
              <!-- page-size 表示当前页的容量 每页几条数据 -->
              <!-- layout 表示分页的展示样式 -->
              <!-- total 表示 一共有多少条数据 -->
              <!-- @current-change 表示点击页码时执行的事情 -->
              <!-- @size-change 表示动态设置页容量的时候执行的事情 -->
              <el-pagination
                :current-page="page"
                :page-sizes="[2, 3, 4, 5]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
              />
            </div>
          </el-tab-pane>

          <el-tab-pane label="公司信息">
            <!-- 公司信息 -->
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input
                  v-model="companyForm.name"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="companyForm.companyAddress"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  v-model="companyForm.mailbox"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="companyForm.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 弹框 -->
    <el-dialog
      :title="showTitle"
      :visible="showDialog"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="form.description" placeholder="请输入角色描述" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitBtn">确认</el-button>
      </template>
    </el-dialog>
    <!-- 分配权限的弹层 -->
    <el-dialog
      title="分配权限"
      :visible="showAssignDialog"
      :close-on-click-modal="false"
      @close="closeAssignDialog"
      @open="dialogOpenFn"
    >
      <!-- show-checkbox 数据可选 -->
      <!-- check-strictly 父级数据与二级数据不关联 -->
      <!-- node-key 使用key数据回显 -->
      <el-tree
        ref="tree"
        v-loading="isTreeLoading"
        :data="permissionList"
        :props="{ label: 'name' }"
        show-checkbox
        check-strictly
        default-expand-all
        node-key="id"
      />
      <template #footer>
        <div style="text-align: right">
          <el-button @click="closeAssignDialog">取消</el-button>
          <el-button type="primary" @click="assignPerm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoleListApi,
  delRoleListApi,
  addRoleListApi,
  getRoleDateApi,
  editRoleListApi,
  getCompanyInfoApi,
  assignPermApi
} from '@/api/setting'
import { getPermissionListApi } from '@/api/permission'
import { transListToTreeData } from '@/utils/index'
import { mapGetters } from 'vuex'
export default {
  name: 'Setting',
  data() {
    return {
      page: 1,
      pagesize: 2,
      roleList: [],
      total: 0,
      isLoading: false,
      showDialog: false,
      showAssignDialog: false,
      roleId: '',
      permissionList: [],
      isTreeLoading: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不可为空', trigger: 'blur' }]
      },
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      }
    }
  },
  computed: {
    ...mapGetters(['companyId']),
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    // 给角色分配权限
    async assignPerm() {
      // console.log(this.$refs.tree.getCheckedNodes())
      // console.log(this.$refs.tree.getCheckedKeys())
      const permIds = this.$refs.tree.getCheckedKeys()
      await assignPermApi({ id: this.roleId, permIds })
      this.$message.success('分配权限成功')
      this.closeAssignDialog()
    },
    // 权限弹框打开
    async dialogOpenFn() {
      this.isTreeLoading = true
      await this.getPermissionList()
      await this.getPermissionDetailFn()
      this.isTreeLoading = false
    },
    // 回显已有的权限
    async getPermissionDetailFn() {
      const {
        data: { permIds }
      } = await getRoleDateApi(this.roleId)
      // console.log(permIds)
      this.$refs.tree.setCheckedKeys(permIds)
    },
    // 获取全部权限数据
    async getPermissionList() {
      const { data } = await getPermissionListApi()
      // console.log(data)
      this.permissionList = transListToTreeData(data, '0')
    },
    // 分配权限弹框显示
    showAssignDialogFn(id) {
      this.roleId = id
      this.showAssignDialog = true
    },
    // 分配权限弹框关闭
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    // 获取公司信息
    async getCompanyInfo() {
      const { data } = await getCompanyInfoApi(this.companyId)
      // console.log(data)
      this.companyForm = data
    },
    // 编辑角色
    async editRoleList(id) {
      const { data } = await getRoleDateApi(id)
      // console.log(data)
      //   // 数据回显
      this.form = data
      this.showDialog = true
    },
    // 获取角色列表
    async getRoleList() {
      this.isLoading = true
      const { data } = await getRoleListApi(this.page, this.pagesize)
      // console.log(data)
      this.roleList = data.rows
      this.total = data.total
      this.isLoading = false
    },
    // 点击页码
    handleCurrentChange(val) {
      // console.log(val)
      this.page = val
      this.getRoleList()
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.getRoleList()
      // console.log(val)
    },
    // 序号
    indexMethod(index) {
      // console.log(index)
      return (this.page - 1) * this.pagesize + index + 1
    },
    // 删除角色
    delRoleList(id) {
      // console.log(id)
      this.$confirm('确认要删除该角色吗?', '温馨提示')
        .then(async() => {
          await delRoleListApi(id)
          if (this.roleList.length === 1 && this.page > 1) {
            this.page--
          }
          this.$message.success('删除成功')
          this.getRoleList()
        })
        .catch(() => {})
    },
    // 关闭弹框
    closeDialog() {
      // 关闭弹框
      this.showDialog = false
      this.$refs.roleForm.resetFields()
      // 手动重置表单
      this.form = {
        name: '',
        description: ''
      }
    },
    // 添加角色
    addRoleList() {
      this.showDialog = true
    },
    // 点击弹框确认添加
    submitBtn() {
      // 兜底校验
      this.$refs.roleForm.validate(async(valid) => {
        if (!valid) return
        if (this.form.id) {
          // 编辑操作
          await editRoleListApi(this.form)
          this.$message.success('修改成功')
        } else {
          // 校验通过
          await addRoleListApi(this.form)
          this.$message.success('添加成功')
        }
        this.getRoleList()
        this.closeDialog()
      })
    }
  }
}
</script>

<style>
</style>
